import React from 'react';
import { Button, Form, Input , notification } from 'antd';
import service from '../../api';
import './login.scss'
import { useDispatch } from 'react-redux'
import { useNavigate} from 'react-router-dom'

  interface Props {}

function Login(props:Props) {

  var dispatch = useDispatch()
  var navigate = useNavigate()


   // 表单验证通过时执行
    const onFinish =async (values: any) => {
    console.log('Success:', values);
    // 发起登陆请求
    var res = await service.admin.admin_login(values)
    notification.destroy()
    // console.log(res.data);
    if( res.data.code == 200){
      notification.success({message:res.data.message})
      dispatch({type:'SAVE_USERINFO',payload:res.data.data})
      navigate('/index')
    }else{
      notification.error({message:'登陆失败'})
    }
  }; 

  // 验证手机号
  var adminnamevalidator = (rule:any, value:any, callback:any) => {
    if( value.length < 7 || value == 'admin'){
      callback();
    }else{
      callback(new Error('请输入正确的手机号作为登录账号'));
    }
  }
  // 验证密码
  var passwordvalidator = (rule:any, value:any, callback:any) => {
    if( /^\d{6}$/.test(value) ){
      callback();
    }else{
      callback(new Error('请输入符合格式的密码'));
    }
  }

  return (
    <div className='login'>
      <div className="title">嗨购后台管理系统</div>
      <Form className='form'
        initialValues={{ remember: true }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          name="adminname"
          rules={[{ validator:adminnamevalidator }]}
        >
          <Input placeholder='请输入账号'/>
        </Form.Item>

        <Form.Item
          name="password"
          rules={[{ validator:passwordvalidator }]}
        >
          <Input.Password placeholder='请输入密码'/>
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" block>
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}

export default Login;